package org.third.integration.kubernates.cmd.imp;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.entity.ByteArrayEntity;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.third.common.utils.StreamUtils;
import org.third.integration.kubernates.cmd.KubectlPatch;
import org.third.integration.kubernates.cmd.imp.api.K8sApiBuilder;
import org.third.integration.kubernates.cmd.imp.bean.KubeApiInstanceInfo;
import org.third.integration.kubernates.cmd.imp.client.KubeRquestClient;
import org.third.integration.kubernates.cmd.imp.client.bean.ApiServerResponse;
import org.third.integration.kubernates.cmd.imp.exp.RequestApiServerException;

@Component
public class KubectlPatchImpl implements KubectlPatch {
	
	@Autowired
	private K8sApiBuilder k8sApiBuilder;

	@Autowired
	private KubeRquestClient kubeRquestClient;

	private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public KubeApiInstanceInfo executePatch(String type, String apiVersion, String namespace, String instanceName,String urlArgs, String bodyArgs) throws RequestApiServerException {
		//拼接URL
		KubeApiInstanceInfo kubeApiInstanceInfo= new KubeApiInstanceInfo(type,apiVersion,namespace,instanceName,urlArgs,bodyArgs);

		return kubeApiInstanceInfo = requestK8s(kubeApiInstanceInfo);
		
	}
	
	private KubeApiInstanceInfo requestK8s(KubeApiInstanceInfo kubeApiInstanceInfo) throws RequestApiServerException {
		String url = k8sApiBuilder.buildAPI(kubeApiInstanceInfo.getNamespace(), kubeApiInstanceInfo.getApiVersion(), kubeApiInstanceInfo.getType(),kubeApiInstanceInfo.getInstanceName());
		logger.debug("url:"+url);
		String jsonString = kubeApiInstanceInfo.getBoyArgs();
		HttpPatch httpPatch = new HttpPatch(url);  
		httpPatch.setHeader("Content-Type", "application/strategic-merge-patch+json");
		HttpEntity entity = new ByteArrayEntity(StreamUtils.stringToUtf8Bytes(jsonString));
		httpPatch.setEntity(entity);
		ApiServerResponse apiServerResponse = kubeRquestClient.requestK8s(httpPatch);
		kubeApiInstanceInfo.setStatusCode(apiServerResponse.getStatusCode());
		kubeApiInstanceInfo.setResponseBody(apiServerResponse.getResponseBody());
		if(apiServerResponse.getException() != null){
			throw new RequestApiServerException("Failed to request API server", apiServerResponse.getException());
		}

		return kubeApiInstanceInfo;
	}

}
